<template>
  <div>
    <div class="xw-block">
      <el-input placeholder="请输入你要搜索的菜单名称" style="width: 300px" v-model="menuName" clearable @clear="clearSearch">
      </el-input>
      <el-button type="primary" style="margin-left: 10px" @click="seacher">搜索</el-button>
    </div>
    <div class="xw-block">
      <el-button type="primary" @click="addMenu">新增菜单</el-button>
    </div>
    <el-table
        class="xw-block-table"
        :data="tableData"
        row-key="id"
        border
        :tree-props="{children: 'children',hasChildren: 'hasChildren'}"
    >
      <el-table-column label="菜单图标">
        <template slot-scope="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="menuName" label="菜单名称"></el-table-column>
      <el-table-column prop="path" width="130" label="跳转路径"></el-table-column>
      <el-table-column prop="name" width="130" label="路由名称"></el-table-column>
      <el-table-column prop="filePath" label="文件名称" width="230"></el-table-column>
      <el-table-column label="令牌认证">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isToken == 0" type="warning">需要令牌</el-tag>
          <el-tag v-if="scope.row.isToken == 1" type="success">不需要令牌</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否显示">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isShowMenu == 0" type="warning">显示</el-tag>
          <el-tag v-if="scope.row.isShowMenu == 1" type="success">不显示</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序数字"></el-table-column>
      <el-table-column width="200" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定要删除吗？"
              @confirm="del(scope.row)"
          >
            <el-button slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <MyDrawer ref="MyDrawer" :title="selectRow.id ? '修改菜单' : '新增菜单'" @saveOrUpdate="saveOrUpdate" @close="clearForm">
      <el-form
          ref="menuForm"
          :model="selectRow"
          label-position="top"
          class="line"
          :rules="rules"
      >
        <el-form-item label="父菜单">
          <el-select style="width: 100%" placeholder="请选择父菜单" v-model="selectRow.parentId" clearable>
            <el-option v-for="(parent, parentIndex) in parentMenu" :key="parentIndex" :label="parent.menuName" :value="parent.id">
              <div style="font-size: 18px">
                <i :class="parent.icon" />
                <span style="margin-left: 10px">{{ parent.menuName }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="selectRow.menuName" placeholder="请填写菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="跳转路径">
          <el-input v-model="selectRow.path" placeholder="请填写跳转路径"></el-input>
        </el-form-item>
        <el-form-item label="路由名称">
          <el-input v-model="selectRow.name" placeholder="请填写路由名称"></el-input>
        </el-form-item>
        <el-form-item label="文件名称">
          <el-input v-model="selectRow.filePath" placeholder="请填写文件名称，该文件只能在/views/back 目录下"></el-input>
        </el-form-item>
        <el-form-item label="是否需要令牌验证">
          <el-switch
              v-model="selectRow.isToken"
              active-color="#131ce66"
              inactive-color="#ff4946"
              :active-value="0"
              :inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否显示在左侧菜单">
          <el-switch
              v-model="selectRow.isShowMenu"
              active-color="#131ce66"
              inactive-color="#ff4946"
              :active-value="0"
              :inactive-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="selectRow.sort" type="number" placeholder="请输入排序数字"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标">
          <el-select v-model="selectRow.icon" placeholder="请选择菜单图标" style="width: 100%">
            <el-option v-for="(icon, iconIndex) in iconList" :key="iconIndex" :label="icon.value" :value="icon.value">
              <div style="font-size: 18px">
                <i :class="icon.value"></i>
                <span style="margin-left: 10px">{{ icon.value }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </MyDrawer>

  </div>
</template>
<script>
import MyDrawer from "@/components/MyDrawer.vue";

export default {
  data() {
    return {
      iconList: [],
      parentMenu: [],
      selectRow: {
        isToken: 0,
        isShowMenu: 0
      },
      menuName: "",
      tableData: [],
      rules: {
        menuName: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序字段不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  components: {MyDrawer},
  mounted() {
    this.load()
    this.parentMenuList()
    this.getIconList()
    this.filteredTableData = [...this.tableData]; // 初始化过滤后的数据
  },
  methods: {
    del(row) {
      this.request.delete("/menu/delMenu?menuId=" + row.id).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功")
          this.load()
        } else {
          this.messageError(res.msg)
        }
      })
    },

    load() {
      this.request.get("/menu/menuList").then(res => {
        if (res.code === '200') {
          this.tableData = res.data
        }
        this.filteredTableData = [...this.tableData]; // 更新过滤后的数据
      })
    },
    // 获取父菜单
    parentMenuList() {
      this.request.get("/menu/parentMenuList").then(res => {
        if (res.code === '200') {
          this.parentMenu = res.data
        }
      })
    },
    // 获取图标列表
    getIconList() {
      this.request.get("/menu/iconList").then(res => {
        if (res.code === '200') {
          this.iconList = res.data
        }
      })
    },
    // 搜索
    seacher() {
      const searchKeyword = this.menuName.trim();
      if (searchKeyword === '') {
        // 如果搜索关键词为空，则加载全部数据
        this.load();
      } else {
        // 递归搜索菜单数据
        const searchMenuData = (data, keyword) => {
          return data.filter(item => {
            // 匹配菜单名称
            if (item.menuName.includes(keyword)) {
              return true;
            }
            // 如果存在子菜单，则递归搜索子菜单
            if (item.children && item.children.length > 0) {
              const filteredChildren = searchMenuData(item.children, keyword);
              if (filteredChildren.length > 0) {
                item.children = filteredChildren; // 更新子菜单为过滤后的结果
                return true;
              }
            }
            return false;
          });
        };

        // 使用递归搜索方法更新tableData
        this.tableData = searchMenuData(this.tableData, searchKeyword);
      }
    },
    // 清空搜索
    clearSearch() {
      this.menuName = '';
      this.load(); // 可选：清空后重新加载数据
    },
    // 新增菜单
    addMenu() {
      this.selectRow = { isToken: 0, isShowMenu: 0 }; // 初始化数据
      if (this.$refs.menuForm) {
        this.$refs.menuForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open(); // 打开抽屉
    },
    // 编辑菜单
    edit(row) {
      this.selectRow = { ...row }; // 填充需要编辑的数据
      if (this.$refs.menuForm) {
        this.$refs.menuForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open(); // 打开抽屉
    },
    //保存或修改菜单
    saveOrUpdate() {
      this.$refs.menuForm.validate(valid => {
        if (!valid) {
          this.messageError('请检查必填项是否填写完整'); // 添加此提示信息
          return; // 如果校验未通过，直接返回
        }

        if (!this.selectRow.id) {
          this.request.post("/menu/addMenu", this.selectRow).then(res => {
            if (res.code === '200') {
              this.messageSuccess("菜单新增成功");
              this.$refs.MyDrawer.close(); // 关闭抽屉
              this.load(); // 重新加载数据
            } else {
              this.messageError(res.msg);
            }
          });
        } else {
          this.request.post("/menu/updateMenu", this.selectRow).then(res => {
            if (res.code === '200') {
              this.messageSuccess("菜单修改成功");
              this.$refs.MyDrawer.close(); // 关闭抽屉
              this.load(); // 重新加载数据
            } else {
              this.messageError(res.msg);
            }
          });
        }
      });
    },

    clearForm() {
      this.$refs.menuForm.resetFields(); // 重置表单
    }
  }
}
</script>
<style></style>
